<?php
namespace App\Repository\Db;

use App\Repository\Contracts\MenuInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 14:49
 *
 * @Description:
 */
class MenuRepository extends Repository implements MenuInterface
{
    protected $rules = [
        'created' => [
            'name' => 'required|min:2|max:16|unique:menu,name',
            'url' => 'required|min:2|max:16|unique:menu,url',
            'parent_id' => 'sometimes|integer',
            'sort' => 'sometimes|integer',
            'status' => 'sometimes|integer'
        ],
        'updated' => [
            'name' => 'required|min:2|max:16|unique:menu',
            'url' => 'required|min:2|max:16|unique:menu',
            'parent_id' => 'sometimes|integer',
            'sort' => 'sometimes|integer',
            'status' => 'sometimes|integer'
        ]
    ];

    protected $messages = [
        'name.required' => "菜单名不能为空",
        'name.min' => "菜单名不能少于2个字",
        'name.max' => "菜单名不能多于8个字",
        'name.unique' => "菜单名不能重复",
        'url.required' => "菜单 URL 不能为空",
        'url.min' => "菜单 URL 不能少于2个字",
        'url.max' => "菜单 URL 不能多于8个字",
        'url.unique' => "菜单 URL 不能重复",
        'parent_id.required' => "父级 ID 不能为空",
        'sort.min' => "排序不能少于2个汉字",
        'status.max' => "状态不能多于32个汉字"
    ];

    protected function modelName()
    {
        return 'App\Model\Menu';
    }

    public function lists($ids = [], $isParent = 0)
    {
        $result = [];
        $query = $this->model;
        if ($ids) {
            $query = $query->whereIn('id', $ids);
        }
        if ($isParent) {
            $query = $query->where('parent_id', '=', 0);
        }
        $menu = $query->where('status', 1)->orderBy('id', 'asc')->get()->toArray();

        // 获取菜单
        foreach ($menu as $val) {
            if (!$val['parent_id']) {
                $result[$val['id']] = $val;
            } else {
                $result[$val['parent_id']]['children'][] = $val;
            }
        }

        return array_values($result);
    }

    public function detail($id)
    {
        return $this->find($id);
    }

    public function created(array $data)
    {
        // 表单验证
        $this->validate($data, 'created');

        return $this->save($data);
    }

    public function updated($id, array $data)
    {
        // 表单验证
        $this->validate($data, 'updated', ['name' => $id, 'url' => $id]);

        return $this->update($data, $id, 'id');
    }
}